package com.baiduspring.service.user.impl;

import com.baiduspring.dao.entity.UserDetails;
import com.baiduspring.dao.mapper.UserDetailsMapper;
import com.baiduspring.error.BaiduSpringException;
import com.baiduspring.service.user.UserDetailsService;
import com.baiduspring.vo.UserDetailsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Optional;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserDetailsMapper userDetailsMapper;

    @Override
    public Optional<UserDetails> getByAccount(Long account) {
        return Optional.ofNullable(userDetailsMapper.selectByAccount(account));
    }

    @Override
    public void merge(UserDetailsVO vo) {
        Optional<UserDetails> userDetails = this.getByAccount(vo.getAccount());
        if (userDetails.isPresent()) {
            this.modify(vo.setId(userDetails.get().getId()));
        } else {
            this.create(vo);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(UserDetailsVO vo) {
        UserDetails userDetails = vo.conver(vo, new UserDetails());
        try {
            int rows = userDetailsMapper.insertSelective(userDetails);
            if (rows == 0) {
                throw new BaiduSpringException("抱歉，发生了小异常，请刷新重新操作");
            }
        } catch (BaiduSpringException e) {
            log.error("创建用户详情信息错误：{}", e);
            e.setErrorMsg("操作异常");
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modify(UserDetailsVO vo) {
        UserDetails userDetails = vo.conver(vo, new UserDetails());
        try {
            int rows = userDetailsMapper.updateByPrimaryKeySelective(userDetails);
            if (rows == 0) {
                throw new BaiduSpringException("抱歉，发生了小异常，请刷新重新操作");
            }
        } catch (BaiduSpringException e) {
            log.error("更新用户详情信息错误：{}", e);
            e.setErrorMsg("操作异常");
            throw e;
        }
    }
}
